// 配置路由
import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/login'
import Layout from '@/views/layout'
import NotFound from '@/views/404'
import Home from '@/views/layout/Home'
import QA from '@/views/layout/QA'
import Video from '@/views/layout/Video'
import User from '@/views/layout/User'
import store from '@/store'
import UserEdit from '@/views/layout/User/edit'
import Search from '@/views/search'



// 解决路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}


Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: '',
        component: Home
      },
      {
        path: 'qa',
        component: QA
      },
      {
        path: 'video',
        component: Video
      },
      {
        path: 'user',
        component: User
      }
    ]
  },
  {
    path: '/user/edit',
    component: UserEdit
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/search',
    component: Search
  },
  {
    path: '*',
    component: NotFound
  }
]
const router = new VueRouter({
  routes
})

// 前置导航守卫
// to从哪来
// from: 到哪去
// next() next代表放行，如果next()  如果next('/login')
// 1.判断是否有token
// 2.判断是否有to肯，直接放行
// 3.如果没有token,也不能直接拦到登录页
// 4.继续判断 去的页面是否需要登录
// 5.如果去的页面需要登录，比如 /user /chat,拦截到 /login
// 6.如果去的页面不需要登录，比如 /login /home ， 直接放行
// 需要登录才能访问的地址
const loginUrls = ['/user', '/user/edit', '/chat']
router.beforeEach(function (to, from, next) {
  // console.log('to', to)
  // console.log('from', from)
  const token = store.state.user.token.token
  if (token) {
    // 有token
    return next()
  }
  // 判断to的路径 没有token
  if (loginUrls.includes(to.path)) {
    // next('/login')
    router.push({
      path: '/login',
      query: {
        back: to.path
      }
    })
  } else {
    next()
  }
})
// window.router = router

export default router
